package com.baoxin.chenxixc4coach.dialog;

import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baoxin.chenxixc4coach.AudioRecordActivity;
import com.baoxin.chenxixc4coach.MyApplication;
import com.baoxin.chenxixc4coach.MyCallback;
import com.baoxin.chenxixc4coach.R;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.NetUtil;
import com.baoxin.chenxixc4coach.utils.TimeTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

public class AudioEditDialog extends BaseDialogFragment {

    private ImageView mShiTing;//试听
    private MediaPlayer mp;
    private TextView mTime;
    private ImageView mSave;
    private ImageView mUpload;
    private LoadingDialog loadingDialog;
    private EditText mName;
    private EditText mContent;
    private Handler handler;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.audio_edit, container, false);
        mShiTing = view.findViewById(R.id.shiting);
        mTime = view.findViewById(R.id.time);
        mSave = view.findViewById(R.id.save);
        mUpload = view.findViewById(R.id.upload);
        mName = view.findViewById(R.id.name);
        mContent = view.findViewById(R.id.beizhu);
        mShiTing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playAudio();
            }
        });
        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newName = mName.getText().toString();
                if (newName.length() == 0) {
                    Toast.makeText(getActivity(), "命名为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                File des = new File(AudioRecordActivity.getAudioDir(getActivity()) + File.separator + newName);
                File src = new File(getTag());//getTag == filePath
                src.renameTo(des);
                Toast.makeText(getActivity(), "保存成功！", Toast.LENGTH_SHORT).show();
                dismiss();
            }
        });

        mUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newName = mName.getText().toString();
                if (newName.length() == 0) {
                    Toast.makeText(getActivity(), "命名为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                File des = new File(AudioRecordActivity.getAudioDir(getActivity()) + File.separator + newName);
                File src = new File(getTag());//getTag == filePath
                src.renameTo(des);

                LoadingDialog.Builder builder = new LoadingDialog.Builder(getActivity());
                builder.setCancelable(false);
                builder.setMessage("上传中...");
                builder.setShowMessage(true);
                loadingDialog = builder.create();
                loadingDialog.show();
                uploadAudioCourse(des.getAbsolutePath());
            }
        });

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        loadingDialog.dismiss();
                        Toast.makeText(getActivity(), "上传成功！", Toast.LENGTH_SHORT).show();
                        dismiss();
                        break;
                    default:
                        loadingDialog.dismiss();
                        Toast.makeText(getActivity(), "上传失败！", Toast.LENGTH_SHORT).show();

                }
            }
        };

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        mp = new MediaPlayer();
        try {
            mp.setDataSource(getTag());
            mp.prepare();
            mTime.setText(TimeTools.getHHmmssByLong(mp.getDuration()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void playAudio() {
        mp.start();
    }

    private void uploadAudioCourse(String loaclAudioPath) {

        final String netAudioPath = "avatar/" + mName.getText().toString();
        PutObjectRequest put = new PutObjectRequest("bxpeter", netAudioPath, loaclAudioPath);

        OSSAsyncTask task = MyApplication.oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());

                audioAdd(netAudioPath);

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    private void audioAdd(String netAudioPath) {
        JSONObject body = new JSONObject();
        try {
            body.put("url", netAudioPath);
            body.put("auName", mName.getText().toString());
            body.put("auContent", mContent.getText().toString());
            body.put("auTime", mTime.getText().toString());
            NetUtil.post(activity, Interfaces.URL_ADD_AUDIO, body.toString(), new MyCallback(Interfaces.URL_ADD_AUDIO, handler));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mp != null) {
            mp.stop();
            mp.release();
            mp = null;
        }
    }
}
